import { useIntersectionObserver, useIntervalFn } from "@vueuse/core"
import { ref } from "vue"

export function useLazyData(callback: () => void) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
    if (isIntersecting) {
      // 进入可视区要做的事情 ?
      callback()
      // 停止监视, 以后不会再触发
      stop()
    }
  }, {
    // 阈值 threshold [ˈθreʃhoʊld]
    threshold: 0
  })
  return target
}

export function useCountDown(count: number) {
  const time = ref(0)
  // 专门做倒计时
  // pause: 暂停
  // resume: 继续
  const { pause, resume } = useIntervalFn(() => {
    time.value--
    if (time.value === 0) pause()
  }, 1000, {
    immediate: false
  })

  const start = () => {
    if (time.value > 0) return
    time.value = count
    resume()
  }

  return {
    time,
    resume,
    start
  }
}